/**
 * Copyright (C) 2021 - 2031 O-Cubes Co., Ltd.
 */

/****************************************************************
 *  @file    spi_slave_test.c
 *  @brief   SPI Slave testcase source file
 *  @version v1.0
 *  @date    03. Apr. 2023
 ****************************************************************/

#include "hal_api.h"
#include "printf.h"
#include "pcl.h"
#include "device_spi.h"

int32_t test_spi_slave(void)
{
	uint8_t read_buf[2] = {0};
	uint8_t write_buf[2] = {0xaa, 0x55};
	DEV_SPI_PTR spi_ptr = spi_get_dev(DW_SPI_2_ID);

	printf("\r\n[SPI SLAVE]: TEST START\r\n");

	Hal_Pcl_FuncSet(PAD_ID_GPIO08, PAD020_FUNC_SPI2_CSN);
	Hal_Pcl_PdPuSet(PAD_ID_GPIO08, PCL_PD_PU_ENABLE);
	Hal_Pcl_OutputSet(PAD_ID_GPIO08, PCL_OUTPUT_DISABLE);

	Hal_Pcl_FuncSet(PAD_ID_GPIO09, PAD021_FUNC_SPI2_CLK);
	Hal_Pcl_PdPuSet(PAD_ID_GPIO09, PCL_PD_PU_ENABLE);
	Hal_Pcl_OutputSet(PAD_ID_GPIO09, PCL_OUTPUT_DISABLE);

	Hal_Pcl_FuncSet(PAD_ID_GPIO10, PAD022_FUNC_SPI2_SDIO);
	Hal_Pcl_PdPuSet(PAD_ID_GPIO10, PCL_PD_PU_ENABLE);
	Hal_Pcl_OutputSet(PAD_ID_GPIO10, PCL_OUTPUT_DISABLE);

	Hal_Pcl_FuncSet(PAD_ID_GPIO11, PAD023_FUNC_SPI2_SDO);
	Hal_Pcl_PdPuSet(PAD_ID_GPIO11, PCL_PD_PU_DISABLE);
	Hal_Pcl_OutputSet(PAD_ID_GPIO11, PCL_OUTPUT_ENABLE);


	spi_ptr->spi_open(DEV_SLAVE_MODE, SPI_CLK_MODE_DEFAULT);

	while (1) {
		spi_ptr->spi_read(write_buf, 2, read_buf, 2);

		printf("[SPI SLAVE]: recv data 0x%02x 0x%02x\r\n", read_buf[0], read_buf[1]);
		if(read_buf[0] == 0xa5 && read_buf[1] == 0x5a)
			break;

		Hal_Cnt_DelayMs(1000);
	}

	Hal_Pcl_FuncSet(PAD_ID_GPIO08, PAD020_FUNC_UART4_TXD);
	Hal_Pcl_PdPuSet(PAD_ID_GPIO08, PCL_PD_PU_DISABLE);
	Hal_Pcl_OutputSet(PAD_ID_GPIO08, PCL_OUTPUT_ENABLE);

	Hal_Pcl_FuncSet(PAD_ID_GPIO09, PAD021_FUNC_UART4_RXD);
	Hal_Pcl_PdPuSet(PAD_ID_GPIO09, PCL_PD_PU_ENABLE);
	Hal_Pcl_OutputSet(PAD_ID_GPIO09, PCL_OUTPUT_DISABLE);

	Hal_Pcl_FuncSet(PAD_ID_GPIO10, PAD022_FUNC_UART4_RTS);
	Hal_Pcl_PdPuSet(PAD_ID_GPIO10, PCL_PD_PU_DISABLE);
	Hal_Pcl_OutputSet(PAD_ID_GPIO10, PCL_OUTPUT_ENABLE);

	Hal_Pcl_FuncSet(PAD_ID_GPIO11, PAD023_FUNC_UART4_CTS);
	Hal_Pcl_PdPuSet(PAD_ID_GPIO11, PCL_PD_PU_ENABLE);
	Hal_Pcl_OutputSet(PAD_ID_GPIO11, PCL_OUTPUT_DISABLE);


	printf("[SPI SLAVE]: TEST END\r\n");

	return 0;
}
